var express = require("express");
var router = express.Router();
var { insertUser,Select,SelectByid, deleteUser, showListUser,updateUserById } = require("../module/AdminModel");
var { ParseToken } = require("../utils/token");
/* GET home page. */
//验证用户是否带有token过来
router.post("/*", async function (req, res, next) {
  if(!req.headers['x-token']){
    res.send({code:-1,msg:"token 缺失"})
  }else{
    next();
  }
});

router.post("/insert", async function (req, res, next) {
  //获取用户传递过来的token
  var token = req.headers['x-token']
  // 解析token 验证用户
  let user = ParseToken(token)

  if(user){
    let userinfo = await Select(user)
    let {level} = userinfo
    if(!(level>1)){
      const {username,password,level} = req.body;
      const result = await insertUser({username,password,level});
      res.send(result?{code:0,msg:"添加成功"}:{code:-1,msg:"用户已存在"})
    }else{
      res.send({code:-2,msg:"您未拥有添加权限，请先提升权限"})
    }
  }else{
    res.send({code:-1,msg:"token失效"})
  }
});
// 删除用户（一般是leader 操作）
router.post("/delete",async function (req, res, next) {
   //获取用户传递过来的token
   var token = req.headers['x-token']
   // 解析token 验证用户
   let user = ParseToken(token)
   if(user){
     let userinfo = await Select(user)
     let {level} = userinfo
     if(!(level>1)){
      // 这里需要一个被删除的用户的_id
      await deleteUser(req.body)
      //删除用户之后再去查找，验证是否删除成功
      const result =await SelectByid(req.body._id);
      res.send((!result)?{code:0,msg:"删除成功"}:{code:-1,msg:"删除失败"})
     }else{
       res.send({code:-2,msg:"您未拥有添加权限，请先提升权限"})
     }
   }else{
     res.send({code:-1,msg:"token失效"})
   }
});
// 修改数据密码和权限
router.post("/updata",async function (req, res, next) {
  //获取用户传递过来的token
  var token = req.headers['x-token']
  // 解析token 验证用户
  let user = ParseToken(token)
  if(user){
    let userinfo = await Select(user)
    let uplevel = userinfo.level  
    const {_id,username,password,level} = req.body
    if(uplevel<=level){
      let result = await updateUserById(_id,{username,password,level})
      res.send({code:0,msg:"修改成功"})
    }else{
      res.send({code:-1,msg:"您的权限不够，请先提升权限"})
    }
  }else{
    res.send({code:-1,msg:"token失效"})
  }
});
router.post("/select", function (req, res, next) {
  console.log(req.body);
  res.send({ result: false });
});
// 展示所有下游管理员
router.post("/selectAll",async function (req, res, next) {
  //获取用户传递过来的token
  var token = req.headers['x-token']
  // 解析token 验证用户
  let user = ParseToken(token)
  if(user){
    let userinfo = await Select(user)
      let result = await showListUser({ level: { '$gte': `${userinfo.level}` } })
      if(result===undefined || result === null ){
        res.send({code:-1,msg:"查询失败"})
      }else {
        res.send({code:0,msg:"查询成功",result:result})
      }
  }else{
    res.send({code:-1,msg:"token失效"})
  }
});



module.exports = router;
